package com.dailyblue.java.cloud.customer.service;

import com.dailyblue.java.cloud.commons.Main;
import com.dailyblue.java.cloud.commons.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class BasicService {
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private RestTemplate restTemplate;

    // 随机
    /*public JsonResult a() {
        log.info("开始请求提供者的内容");
        // 找到这些实例
        List<ServiceInstance> list = discoveryClient.getInstances("example-provider");
        // 获取其中的一个
        int random = (int) (Math.random() * list.size());
        ServiceInstance instance = list.get(random);
        log.info("获取到了{}个提供者,其中一个是:{}", list.size(), instance);
        // 获取url  http://localhost:8010/
        String url = instance.getUri().toString() + "/provider/a";
        log.info("访问路径:{}", url);
        // 调用这个url
        return restTemplate.getForObject(url, JsonResult.class);
    }*/
    // 轮询
    private int i = 0;

    public JsonResult a() {
        log.info("开始请求提供者的内容");
        // 找到这些实例
        List<ServiceInstance> list = discoveryClient.getInstances("example-provider");
        // 获取其中的一个
        ServiceInstance instance = list.get(i);
        if (i == list.size() - 1) {
            i = 0;
        } else {
            i++;
        }
        log.info("获取到了{}个提供者,其中一个是:{}", list.size(), instance);
        // 获取url  http://localhost:8010/
        String url = instance.getUri().toString() + "/provider/a";
        log.info("访问路径:{}", url);
        // 调用这个url
        return restTemplate.getForObject(url, JsonResult.class);
    }
}
